﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain.Entity;
using Business;
using Business.Abstract;
using Business.Service;
using PresentationMVC.Models;
using System.Threading;
using Business.Common;

namespace PresentationMVC.Controllers
{
    public class CustomerController : Controller
    {
        #region Actions
        /// <summary>
        /// Load the Custom main page
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            Session.Remove(Constants.CUSTOMER_SEARCH_SESSION);
            CustomerDataModel model = GetCustomerDataModel();
            return View(model);
        }

        /// <summary>
        /// Load the customer in the form to update the details
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(long id)
        {
            ICustomerService srv = new CustomerServiceImpl();
            Customer customer = srv.GetCustomerById(id);
            customer.InitialEmail = customer.Email;
            CustomerDataModel model = GetCustomerDataModel(customer);
            return View("Index", model);
        }

        /// <summary>
        /// Delete the customer 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Delete(long id)
        {
            ICustomerService srv = new CustomerServiceImpl();
            Customer customer = srv.GetCustomerById(id);
            srv.DeleteCustomer(customer);

            ViewData["DELETE_MSG"] = "Successsfully deleted the record.";

            this.ViewData.Model = GetCustomerDataModel();
            return PartialView("_CustomerGridPartial");
        }

        [HttpGet]
        public ActionResult ReloadGrid()
        {
            CustomerDataModel model = GetCustomerDataModel();
            this.ViewData.Model = model;
            return PartialView("_CustomerGridPartial", model);
        }

        [HttpPost]
        public ActionResult GridviewSearch(CustomerDataModel model)
        {
            Session[Constants.CUSTOMER_SEARCH_SESSION] = model;
            this.ViewData.Model = GetCustomerDataModel();
            return PartialView("_CustomerGridPartial");
        }

        /// <summary>
        /// Save the customer details
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(CustomerDataModel model)
        {
            return SaveOrUpdate(model);
        }

        [HttpGet]
        public JsonResult EmailAvailable(CustomerDataModel model)
        {
            if (model.Customer.Email != model.Customer.InitialEmail)
            {
                ICustomerService srv = new CustomerServiceImpl();
                Customer customer = srv.GetCustomerByEmail(model.Customer.Email);
                if (customer == null)
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(string.Format("{0} already exist", Request.QueryString["Customer.Email"]), JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }

        }
        #endregion 

        #region Private Methods
        private CustomerDataModel GetCustomerDataModel()
        {
            return GetCustomerDataModel(null);
        }

        private CustomerDataModel GetCustomerDataModel(Customer customer)
        {
            ICustomerService srv = new CustomerServiceImpl();
            IList<Customer> lstCustomer = new List<Customer>();
            if (Session[Constants.CUSTOMER_SEARCH_SESSION] == null)
            {
                lstCustomer = srv.GetAllCustomers();
            }
            else
            {
                CustomerDataModel search = Session[Constants.CUSTOMER_SEARCH_SESSION]  as CustomerDataModel;
                lstCustomer = srv.GetAllCustomers(search.CustomerSearch.SearchBy, search.CustomerSearch.Value);
            }
            CustomerDataModel model = new CustomerDataModel();
            model.Customer = customer == null ? new Customer() : customer;
            model.AllCustomer = lstCustomer;
            return model;
        }

        

        /// <summary>
        /// Base on the customer object it create a new customer record or update already existing record.
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private ActionResult SaveOrUpdate(CustomerDataModel model)
        {
            Customer customer = model.Customer;
            ICustomerService customerSrv = new CustomerServiceImpl();

            if (ModelState.IsValid)
            {
                try
                {
                    if (customer.ID > 0)
                    {
                        Customer tmpCustomer = customerSrv.GetCustomerById(customer.ID);
                        tmpCustomer.FirstName = customer.FirstName;
                        tmpCustomer.LastName = customer.LastName;
                        tmpCustomer.CompanyName = customer.CompanyName;
                        tmpCustomer.Email = customer.Email;
                        tmpCustomer.AddressLine1 = customer.AddressLine1;
                        tmpCustomer.AddressLine2 = customer.AddressLine2;
                        tmpCustomer.AddressLine3 = customer.AddressLine3;
                        tmpCustomer.City = customer.City;
                        tmpCustomer.County = customer.County;
                        tmpCustomer.Country = customer.Country;
                        tmpCustomer.Postcode = customer.Postcode;
                        tmpCustomer.UpdatedDate = customer.UpdatedDate;
                        tmpCustomer.Title = customer.Title;
                        tmpCustomer.UpdatedDate = DateTime.Now;
                        customerSrv.UpdateCustomer(tmpCustomer);
                        ViewData["MSG"] = "Successfully updated the details.";
                    }
                    else
                    {
                        customerSrv.SaveCustomer(customer);
                        ViewData["MSG"] = "Successfully saved the details.";
                    }

                    ModelState.Clear();
                    customer = new Customer();
                    model.Customer = customer;
                    
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", "Error" + ex.ToString());
                }
            }

            ICustomerService srv = new CustomerServiceImpl();

            model.AllCustomer = srv.GetAllCustomers();
            return RedirectToAction("Index"); ;
        }
        #endregion

    }
}
